package com.jz.banner.screen.banner.ui

import android.annotation.SuppressLint
import android.content.Context
import android.view.View
import android.widget.ImageView
import androidx.viewpager.widget.ViewPager
import cn.jzvd.JZDataSource
import cn.jzvd.Jzvd
import cn.jzvd.Jzvd.*
import cn.jzvd.JzvdStd
import com.alibaba.android.arouter.facade.annotation.Route
import com.jz.banner.screen.R
import com.jz.banner.screen.banner.bean.ClientResFileBean
import com.jz.banner.screen.banner.bean.ResFileBean
import com.jz.banner.screen.banner.bean.SettingInfo
import com.jz.banner.screen.banner.net.GetApi
import com.jz.banner.screen.bean.database.DBBannerStatistical
import com.jz.banner.screen.image.ImageManger
import com.jz.banner.screen.listener.MyObserver
import com.jz.banner.screen.ui.App
import com.jz.banner.screen.ui.activity.base.BaseActivity
import com.jz.banner.screen.utils.*
import com.jz.banner.screen.utils.eventbus.Event
import com.jz.banner.screen.utils.eventbus.EventCode
import com.jz.banner.screen.widget.MyFullJZVideoPlayer
import com.jz.banner.screen.utils.ARouterUtils
import com.youth.banner.BannerConfig
import com.youth.banner.loader.ImageLoader
import io.reactivex.Observable
import io.reactivex.ObservableEmitter
import io.reactivex.ObservableOnSubscribe
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_banner.*

@Route(path = ARouterUtils.BannerActivity)
class BannerActivity : BaseActivity() {
    override fun getContentLayout(): Any = R.layout.activity_banner
    private var isInsert = false

    companion object {
        /*广告设置*/
        var T1 = 5 //称重界面等待的时间跳转商户界面
        var T2 = 5 //商户界面等待的时间跳转广告界面
        var T3 = 10 //广告界面等待的时间跳转商户界面

        //        var T3_1 = 6 //广告界面图片播放的时长
//        var T3_2 = 54 //广告界面视频播放的时长
        var T4 = 3 //广告图之间切换轮播时间

        var mBannerVideoList: MutableList<ResFileBean> = mutableListOf()//当前单个客户的视频播放资源集合

        /* VideoBean(Urls.VIDEO_DEFAULT_URL, Urls.IMAGE_DEFAULT_URL)*/
        var mBannerImageList: MutableList<ResFileBean> = mutableListOf()//当前单个客户的图片播放资源集合

        var mSettingInfo: SettingInfo? = null

        //客户投放广告资源组
        var mClientResFileList: MutableList<ClientResFileBean> = mutableListOf()
    }

    private var mBannerIndex: Int = 0
    private var mVideoIndex: Int = 0
    private var mSeekToInAdvance = 0
    private var mRxSaveStatisticOE: ObservableEmitter<DBBannerStatistical>? = null

    private var mRxSaveStatisticDisposable: Disposable? = null
    private var mFormatterTimeStr = "yyyy-MM-dd HH:mm:ss"


    private var mPollingDisposable: Disposable? = null

    override fun initView() {
    }

    override fun initData() {
        initRxSaveStatistic()
        pollingGetBannerPlayInfo()
    }

    @SuppressLint("CheckResult")
    private fun pollingGetBannerPlayInfo() {
        mPollingDisposable?.dispose()
        Observable.create(ObservableOnSubscribe<String> { e ->
            //TODO:这里还需要判断当前页面是广告页面才能执行。。
            val dbBannerStatistical = getNewDBBannerStatistical(null, 1, null)
            try {
                when {
                    mBanner.visibility == View.VISIBLE -> {
                        val resFileBean = mBannerImageList[mBannerIndex]
                        dbBannerStatistical.launch_id = resFileBean.launch_id
                        dbBannerStatistical.device_id = resFileBean.device_id
                        dbBannerStatistical.material_id = resFileBean.material_id
                    }
                    mJzVideo.visibility == View.VISIBLE -> {
                        val resFileBean = mBannerVideoList[mVideoIndex]
                        dbBannerStatistical.launch_id = resFileBean.launch_id
                        dbBannerStatistical.device_id = resFileBean.device_id
                        dbBannerStatistical.material_id = resFileBean.material_id
                    }
                }
                //以防统计到空的广告信息。
                if (dbBannerStatistical.launch_id != null && dbBannerStatistical.launch_id.isNotBlank()) insertStatistic(dbBannerStatistical)
            } catch (e: Exception) {
                d("pollingGetBannerPlayInfo->onError:$e:")
            }
            e.onComplete()
        })
            .repeatWhen {
                return@repeatWhen it.flatMap {
                    return@flatMap Observable.timer(
                        mSettingInfo?.polling_get_banner_play_info_time ?: 1L,
                        java.util.concurrent.TimeUnit.SECONDS
                    )
                }
            }
            .compose(RxUtils.aLifecycle(this))
            .subscribe(object : MyObserver<String>() {
                override fun onSubscribe(d: Disposable) {
                    mPollingDisposable = d
                }
            })
    }


    /*初始化统计广告播放时长线程*/
    private fun initRxSaveStatistic() {
        //这个用来触发上传不完整订单数据。
        Observable.create(ObservableOnSubscribe<DBBannerStatistical> { oe ->
            mRxSaveStatisticOE = oe
        })
            .observeOn(Schedulers.newThread())
            .subscribe(object : MyObserver<DBBannerStatistical>() {
                override fun onSubscribe(d: Disposable) {
                    mRxSaveStatisticDisposable = d
                }

                override fun onNext(db: DBBannerStatistical) {
                    //触发保存广告播放时信息。
                    App.mDaoSession?.dbBannerStatisticalDao?.insertOrReplaceInTx(db)
                    d("触发保存广告播放时信息:onNext:广告ID:${CommUtils.gson.toJson(db)}")
                }

                override fun onError(t: Throwable) {
                    d("触发保存广告播放时信息:onError:${Thread.currentThread().name},${t}")
                }
            })
    }

    override fun initListener() {
        if (mBannerImageList.isEmpty() && mBannerVideoList.isEmpty()) {
            //TODO:这里初始化默认的图

        }
        //过滤onResume重复调用。
        if (mBannerImageList.size > 1)
            setBannerData()
        else
            if (mBannerImageList.size == 1) mBanner.visibility = View.VISIBLE
        setVideoData()
    }

    /*显示广告图*/
    private fun setBannerData() {
        if (mBannerImageList.isNotEmpty()) mBanner.visibility = View.VISIBLE
        d("setBannerData->mBannerImageList：${mBannerImageList}")
        mBanner.setOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
                //d("OnPageChangeListener->onPageScrolled->position:$position,positionOffset:$positionOffset,positionOffsetPixels:$positionOffsetPixels")
            }

            override fun onPageSelected(position: Int) {
                try {
                    mBannerIndex = position
                    //触发当前播放照片次数+1
                    val resFileBean = mBannerImageList[mBannerIndex]
                    insertStatistic(getNewDBBannerStatistical(resFileBean, null, 1))
                    if (resFileBean.is_last == 1) insertStatistic(getNewDBBannerStatistical(resFileBean, null, null, 1))
                    d("onPageSelected->position：${position}")
                    if (mBannerImageList.size > 0) {
                        if (mBannerImageList.size - 1 == position && mBannerVideoList.isNotEmpty()) {
                            mBanner.postDelayed({
                                mBanner.stopAutoPlay()
                                mBanner.releaseBanner()
                                mBanner.visibility = View.GONE
                                mJzVideo.visibility = View.VISIBLE
                                //连续播放视频
                                try {
                                    d("onPageSelected-->连续播放视频")
                                    val jzDataSource = getJzDataSource(mBannerVideoList[mVideoIndex])
                                    mJzVideo.setUp(jzDataSource, JzvdStd.SCREEN_NORMAL)
                                    mJzVideo.startVideoAfterPreloading();
                                } catch (e: Exception) {
                                    d("onPageSelected-->播放失败：$e")
                                }
                                //放在这里，避免第一张没看到。
                            }, T4 * 1000L - 1000)
                        }
                    } else {
                        goBack()
                    }
                } catch (e: Exception) {
                    goBack()
                }
            }

            override fun onPageScrollStateChanged(state: Int) {
                d("OnPageChangeListener->onPageScrollStateChanged:state:$state")
            }
        })
        mBanner.setImages(mBannerImageList)
            .setBannerStyle(BannerConfig.NOT_INDICATOR)
            .isAutoPlay(true)
            .setBannerAnimation(CommUtils.getBannerAnimation(16))
            .setImageLoader(object : ImageLoader() {
                override fun displayImage(context: Context?, path: Any?, imageView: ImageView) {
                    var item = path as ResFileBean
                    imageView.post {
                        d("ImageBean:Type:${item.scale_type}")
                        ImageManger.setFitCenterImg(this@BannerActivity, item.file_url, imageView, 300)
                        when (item.scale_type) {
                            1 -> {
                                imageView.scaleType = ImageView.ScaleType.CENTER_CROP
                                ImageManger.setCenterCropImg(this@BannerActivity, item.file_url, imageView, 300)
                            }
                            else -> {
                                imageView.scaleType = ImageView.ScaleType.FIT_CENTER
                                ImageManger.setFitCenterImg(this@BannerActivity, item.file_url, imageView, 300)
                            }
                        }
                    }
                }
            })
            .setDelayTime(T4 * 1000)
            .start()
    }

    private fun insertStatistic(dbBannerStatistical: DBBannerStatistical) {
        if (isInsert) mRxSaveStatisticOE?.onNext(dbBannerStatistical)
    }

    private fun getNewDBBannerStatistical(resFileBean: ResFileBean?, play_time: Int?, play_num: Int?, play_launch_num: Int? = null): DBBannerStatistical {
        val rfsb = DBBannerStatistical()
        rfsb.launch_id = resFileBean?.launch_id
        rfsb.device_id = resFileBean?.device_id
        rfsb.material_id = resFileBean?.material_id

        rfsb.play_time = play_time ?: 0
        rfsb.play_num = play_num ?: 0
        rfsb.play_launch_num = play_launch_num ?: 0
        rfsb.play_start_date = CommUtils.toYMD(System.currentTimeMillis() / 1000, mFormatterTimeStr)
        return rfsb
    }

    /*显示视频*/
    private fun setVideoData() {
        mJzVideo.seekToInAdvance
        d("setVideoData--1")
        try {
            if (mBannerVideoList.isEmpty()) {
                mJzVideo.visibility = View.GONE
                Jzvd.releaseAllVideos()
                return
            } else if (mBannerImageList.isEmpty()) {
                mJzVideo.visibility = View.VISIBLE
            }
            d("setVideoData-->")
            val jzDataSource = getJzDataSource(mBannerVideoList[mVideoIndex])

            //难道这里设置循环播放，就不会走那个？
            //jzDataSource.looping = true
            mJzVideo.setUp(jzDataSource, JzvdStd.SCREEN_NORMAL)
            mJzVideo.fullscreenButton.apply {
                visibility = View.INVISIBLE
                this.isClickable = false
            }
            d("setVideoData--4")
            mJzVideo.topContainer.visibility = View.GONE
            mJzVideo.loadingProgressBar.visibility = View.GONE

            d("setVideoData--5")
            mJzVideo.mMyJZVideoPlayerListener = object : MyFullJZVideoPlayer.MyJZVideoPlayerListener {
                override fun onStartPlay() {
                }

                override fun onPausePlay() {
                }

                override fun onPlayComplete() {
                    try {//触发当前播放视频次数+1
                        val resFileBean = mBannerVideoList[mVideoIndex]
                        insertStatistic(getNewDBBannerStatistical(resFileBean, null, 1))
                        if (resFileBean.is_last == 1) insertStatistic(getNewDBBannerStatistical(resFileBean, null, null, 1))
                        val size = mBannerVideoList.size
                        d("onPlayComplete->mBannerVideoList：${mBannerVideoList.size},mBannerVideoList:${size}")
                        when {
                            size > 1 -> go2PlayNextVideo(size)
                            mBannerImageList.isNotEmpty() -> {
                                mBanner.visibility = View.VISIBLE
                                //因为只有一张图时候，banner不会滚动，触发不到onPageSelected
                                if (mBannerImageList.size == 1) setBannerData() else mBanner.startAutoPlay()

                                mJzVideo.visibility = View.GONE
                                JzvdStd.releaseAllVideos()
                                mVideoIndex = 0
                                mSeekToInAdvance = 0
                            }
                            //只有视频时候，估计会出现退出到显示屏，解决：新增size==1,有可能解决。
                            size == 1 -> go2PlayNextVideo(size)
                            else -> goBack()
                        }
                    } catch (e: Exception) {
                        goBack()
                    }
                }

                override fun onStateError() {
                    d("onStateError-->")
                    onPlayComplete()
                }
            }
            mJzVideo.startVideoAfterPreloading();
            d("setVideoData--6")
        } catch (e: Exception) {
            d("视频播放失败1：$e")
        }
    }

    private fun go2PlayNextVideo(size: Int) {
        mVideoIndex++
        d("go2PlayNextVideo->mVideoIndex:$mVideoIndex")
        try {
            when {
                mVideoIndex <= (size - 1) -> {
                    d("go2PlayNextVideo-> 1")
                    //连续播放视频
                    val jzDataSource = getJzDataSource(mBannerVideoList[mVideoIndex])
                    mJzVideo.setUp(jzDataSource, JzvdStd.SCREEN_NORMAL)
                    mJzVideo.startVideoAfterPreloading();
                }
                mBannerImageList.size > 0 -> {
                    d("go2PlayNextVideo-> 2")
                    //视频集合播放完后，开始轮播图片
                    mVideoIndex = 0
                    mBanner.startAutoPlay()


                    mBanner.visibility = View.VISIBLE
                    mJzVideo.visibility = View.GONE
                    JzvdStd.releaseAllVideos()
                }
                else -> {
                    d("go2PlayNextVideo-> 3")
                    //仅有视频情况下
                    mVideoIndex = 0
                    val jzDataSource = getJzDataSource(mBannerVideoList[mVideoIndex])
                    mJzVideo.setUp(jzDataSource, JzvdStd.SCREEN_NORMAL)
                    mJzVideo.startVideoAfterPreloading();
                }
            }
        } catch (e: Exception) {
            d("错误：")
        }
    }

    private fun getJzDataSource(videoBean: ResFileBean): JZDataSource {
        d("setVideoData--2：${CommUtils.gson.toJson(videoBean)}")
        Jzvd.setVideoImageDisplayType(
            when (videoBean.display_type) {
                1 -> VIDEO_IMAGE_DISPLAY_TYPE_FILL_PARENT
                2 -> VIDEO_IMAGE_DISPLAY_TYPE_ADAPTER
                3 -> VIDEO_IMAGE_DISPLAY_TYPE_ORIGINAL
                else -> VIDEO_IMAGE_DISPLAY_TYPE_FILL_SCROP
            }
        );
        //边播放边缓存
        var url = App.getProxy(this)?.getProxyUrl(videoBean.file_url);
        d("setVideoData--3：${url}")
        val jzDataSource = JZDataSource(url, "")
        /*预览图*/
        ImageManger.setCenterCropImg(this, videoBean.cover_url ?: GetApi.IMAGE_DEFAULT_URL, mJzVideo.posterImageView)
        return jzDataSource
    }

    override fun isRegisterEventBus(): Boolean = true
    override fun receiveEvent(event: Event<Any>) {
        super.receiveEvent(event)
        when (event.code) {
            EventCode.BANNER_GO_TO_SHOP_SCREEN -> go2LoginScreen()
            EventCode.BANNER_UPDATE_UI -> initListener()
            EventCode.FINISH_BANNER_SCREEN -> go2LoginScreen()
        }
    }

    override fun onResume() {
        isInsert = true
        try {
            if (mBanner.visibility == View.VISIBLE) {
                //因为只有一张图时候，banner不会滚动，触发不到onPageSelected
                if (mBannerImageList.size == 1) setBannerData() else mBanner.startAutoPlay()
            }
            if (mJzVideo.visibility == View.VISIBLE) {
                mJzVideo.seekToManulPosition = mSeekToInAdvance
                mJzVideo.startVideo()
            }
        } catch (e: Exception) {
            d("视频播放失败2：$e")
        }
        d("onResume:mSeekToInAdvance:${mJzVideo.seekToManulPosition}")
        super.onResume()
    }

    override fun onPause() {
        isInsert = false
        if (mBanner.visibility == View.VISIBLE) {
            mBanner.stopAutoPlay()
        }

        try {
            if (mJzVideo.visibility == View.VISIBLE) {
                mSeekToInAdvance = mJzVideo.seekToManulPosition
            }
            Jzvd.releaseAllVideos()
        } catch (e: Exception) {
            d("视频播放失败3：$e")
        }
        d("onPause:mSeekToInAdvance:$mSeekToInAdvance")
        super.onPause()
    }

    override fun onDestroy() {
        mPollingDisposable?.dispose()
        mRxSaveStatisticOE?.onComplete()
        mRxSaveStatisticDisposable?.dispose()

        super.onDestroy()
    }
}